﻿using System;
using System.IO;
using System.Windows.Forms;

namespace FixImage
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private string imgPath = null;

        private void button1_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == openFileDialog1.ShowDialog())
            {
                imgPath = openFileDialog1.FileName;
            }
            else
            {
                return;
            }

            textBox5.Text = imgPath;
            pictureBox1.Load(imgPath);

            System.Drawing.Image img = System.Drawing.Image.FromFile(imgPath);

            textBox6.Text = string.Format("尺寸大小:{0}x{1}", img.Width, img.Height);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            System.Drawing.Image serverImage = System.Drawing.Image.FromFile(imgPath);

            int toWidth = int.Parse(textBox1.Text.Trim());
            int toHeight = int.Parse(textBox2.Text.Trim());
            int toHRes = int.Parse(textBox4.Text.Trim());
            int toVRes = int.Parse(textBox3.Text.Trim());


            //新建一个bmp图片
            System.Drawing.Bitmap bm = new System.Drawing.Bitmap(toWidth, toHeight);
            bm.SetResolution(toHRes, toVRes);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.White);
            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(serverImage, new System.Drawing.Rectangle(0, 0, toWidth, toHeight), 0, 0, serverImage.Width, serverImage.Height, System.Drawing.GraphicsUnit.Pixel);

            try
            {
                string savePath = Path.GetDirectoryName(imgPath) + Path.GetFileNameWithoutExtension(imgPath) + "-" + textBox1.Text.Trim() + "x" + textBox2.Text.Trim() + ".jpg";
                //以jpg格式保存缩略图
                bm.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                MessageBox.Show("生成照片保存于原目录！");
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                serverImage.Dispose();
                bm.Dispose();
                g.Dispose();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Text = "272";
            textBox2.Text = "354";
            textBox4.Text = "350";
            textBox3.Text = "350";
        }
    }
}
